package ift585.client;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.List;


public class TransactionHandler {
	
	public TransactionHandler() {}
	
	public byte [] doTransaction(List<DatagramPacket> toSend, DatagramSocket commSocket) throws IOException, UnsuccessfulTransactionException{
		
		
		for(DatagramPacket onePacketToSend : toSend){		
			commSocket.send(onePacketToSend);
		}
				
		byte [] dataReceived = new byte[1];
		
		commSocket.setSoTimeout(2000);
		try {
			for(int i = 0 ; i < toSend.size() ; ++i){
				commSocket.receive(new DatagramPacket(dataReceived, dataReceived.length));
			}			
		} catch (SocketTimeoutException e) {
			throw new UnsuccessfulTransactionException();
		}
		
		commSocket.setSoTimeout(0); //reset to no timeout
		
		return dataReceived;
	}
}
